package com.nulldev.util.uri.iwebkit.legacy.elements.text;

import java.awt.Graphics2D;
import java.util.LinkedList;

import com.nulldev.util.java.swing.SwingUtil;
import com.nulldev.util.uri.iwebkit.legacy.element.Element;
import com.nulldev.util.uri.iwebkit.legacy.element.ElementType;

public class TextElement extends Element{

	public TextElement(String id, String classID, String html, String css, String data) {
		super(id, classID, html, css, data, ElementType.TEXT);
	}

	@Override
	public void onLoad() {
	}

	private int prevWidth = -1, prevNH = -1;
	private final LinkedList<String> outs = new LinkedList<String>();

	@Override
	public void onRender(Graphics2D g2d, int x, int y, int width) {
		y += 15;
		this.updateWidth(SwingUtil.stringWidth(g2d.getFontMetrics(), this.getData()));
		this.updateHeight(g2d.getFontMetrics().getHeight() + 2);
		final int len = SwingUtil.stringWidth(g2d.getFontMetrics(), this.getData());
		if (len < width) {
			g2d.drawString(this.getData(), x, y);
		}else {
			if (prevWidth != width) {
				prevWidth = width;
				outs.clear();
				final StringBuilder safeChars = new StringBuilder();
				final StringBuilder safeCharsA = new StringBuilder();
				int loops = 0;
				while (SwingUtil.stringWidth(g2d.getFontMetrics(), safeChars.toString()) < width) {
					safeChars.append(this.getData().charAt(loops));
					loops += 1;
				}

				//System.out.println("Chars before overload: " + loops);
				int corrects = 0;
				while (width > SwingUtil.stringWidth(g2d.getFontMetrics(), safeChars.toString())) {
					final StringBuilder safeChars2 = new StringBuilder();
					final StringBuilder safeChars3 = new StringBuilder();
					int loops2 = 0;
					while (SwingUtil.stringWidth(g2d.getFontMetrics(), safeChars.toString()) < width) {
						safeChars2.append(this.getData().charAt(loops2));
						loops2 += 1;
					}
					corrects += 1;
					safeChars3.append(safeChars2.charAt(safeChars2.length() - 1));
					safeChars2.deleteCharAt(safeChars2.length() - 1);
					safeChars3.append(this.getData().substring(loops2 + 1));
					outs.add(safeChars2.toString());
					outs.add(safeChars3.toString());
				}
				if (corrects == 0) {
					safeCharsA.append(safeChars.charAt(safeChars.length() - 1));
					safeChars.deleteCharAt(safeChars.length() - 1);
					safeCharsA.append(this.getData().substring(loops + 1));
					outs.add(safeChars.toString());
					outs.add(safeCharsA.toString());
				}

				//System.out.println("Chars on new line: " + this.getData().substring(loops).length());
			}
			for (final String out : outs) {
				g2d.drawString(out, x, y);
				y += g2d.getFontMetrics().getHeight() + 2;
				if (prevNH == -1) {
					this.prevNH = this.height() + g2d.getFontMetrics().getHeight() + 2 - 8;
				}
				this.updateHeight(this.prevNH);
			}
		}
	}

}
